<?php
class Lvl_Tour extends ActiveRecord {
	
	protected static $_tableName = 'lvl_tour';
	protected static $_pkName = 'ID_lvl_tour';
	
	public static function getTours() {
		$objDB = Service_Database::instance();
		//$parseDate = substr($objDB->selectSimpleField('SELECT MAX(`created_at`) FROM `lvl_tour`'), 0, 10);

		$arrCountriesIso = $objDB->selectSimpleArray("SELECT DISTINCT `iso` FROM `lvl_tour` WHERE `min_price` < 100000");
		shuffle($arrCountriesIso);
		$arrCountriesIso = array_slice($arrCountriesIso, 0, 4);

		$arrTours = $objDB->select("SELECT * FROM `lvl_tour` WHERE `min_price` < 100000 AND `iso` IN ('" . implode("','", $arrCountriesIso) . "')");
		$arrTours = Service_ArrayConverter::groupArray($arrTours, 'ID_lvl_country');
		
		$arrReturnTours = array();
		foreach ($arrTours as $arrCountryTours) {
			//shuffle($arrCountryTours);
		//	$arrReturnTours[] = $arrCountryTours[0];
			$arrCities = Service_ArrayConverter::getColumn($arrCountryTours, 'city_name_ru');
			shuffle($arrCities);
			$selectCity = $arrCities[0];
			
			$arrCitiesTours = Service_ArrayConverter::groupArray($arrCountryTours, 'city_name_ru');
			$arrCityTours = Service_ArrayConverter::sortArray($arrCitiesTours[$selectCity], 'min_price');
			
			if (count($arrCityTours) > 3) {
				$arrCityTours = array_slice($arrCityTours, 0, ceil(count($arrCityTours) * 0.3));
				shuffle($arrCityTours);
			}
			$arrReturnTours[] = $arrCityTours[0];
		}
		
		return $arrReturnTours;
	}
	
}